package com.aixingfu.sports.ui.activity;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.aixingfu.sports.Adapter.MyAdapter;
import com.aixingfu.sports.MVP.contract.CardTypeContract;
import com.aixingfu.sports.MVP.presenter.CardTypePresenter;
import com.aixingfu.sports.Model.CardTypeModel;
import com.aixingfu.sports.R;
import com.aixingfu.sports.bean.MessageEvent;
import com.aixingfu.sports.bean.Person;
import com.aixingfu.sports.view.CharacterParser;
import com.aixingfu.sports.view.PinyinComparator;
import com.aixingfu.sports.view.SideBar;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.orie.librarybase.base.BaseActivity;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//选择卡片
@Route(path = "/main/SelectCardActivity")
public class SelectCardActivity extends BaseActivity implements CardTypeContract.MyView {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.listview)
    ListView listview;
    @BindView(R.id.sideBar)
    SideBar sideBar;
    @BindView(R.id.tv_dialog)
    TextView mTextDialog;
    MyAdapter myAdapter;

    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    private CardTypePresenter cardTypePresenter;
    private List<CardTypeModel.DataBean> cardTypeList = new ArrayList<>();
    List<Person> list = new ArrayList<>();
    private String venue_id= "";
    @Override
    protected int provideContentViewId() {
        return R.layout.activity_select_card;
    }

    public static void startActivityByRoute() {
        ARouter.getInstance().build("/main/SelectCardActivity").navigation();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        tvTitle.setText("选择卡种");
        Bundle bundle = getIntent().getExtras();
        venue_id = bundle.getString("venue_id", "");
        cardTypePresenter = new CardTypePresenter();
        cardTypePresenter.attachView(this);

        init();
        sideBar.setOnWordsChangeListener(new SideBar.onWordsChangeListener() {
            @Override
            public void wordsChange(String words) {

                    //该字母首次出现的位置
                    int position = myAdapter.getPositionForSection(words.charAt(0));
                    if (position != -1) {
                        listview.setSelection(position);
                    }
            }
        });
        getCardType();

//        list = filledData(getResources().getStringArray(R.array.date));
//        // 根据a-z进行排序源数据
//        Collections.sort(list, pinyinComparator);
//        myAdapter = new MyAdapter(this, list);
//        listview.setAdapter(myAdapter);
    }
    public void getCardType(){
        if (cardTypePresenter.isViewAttached()){
            HashMap<String,String> map = new HashMap<>();
            map.put("venue_id",venue_id);
            cardTypePresenter.getCardType(map);
        }
    }
    private void init() {
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        sideBar.setTextDialog(mTextDialog);
//        View arrowHeader = LayoutInflater.from(this).inflate(R.layout.arrow_header, null);
//        listview.addHeaderView(arrowHeader);
//        View starHeader = LayoutInflater.from(this).inflate(R.layout.star_header, null);
//        listview.addHeaderView(starHeader);
    }
    /**
     * 为ListView填充数据
     *
     * @param
     * @return
     */
    private List<Person> filledData(List<CardTypeModel.DataBean> cardTypeList) {

        List<Person> mSortList = new ArrayList<Person>();

        for (int i = 0; i < cardTypeList.size(); i++) {
            Person sortModel = new Person();
            sortModel.setName(cardTypeList.get(i).getCard_name());
            if (cardTypeList.get(i).getDuration() != null){
                sortModel.setDay(cardTypeList.get(i).getDuration().getDay());
            }
            sortModel.setMax_price(cardTypeList.get(i).getMax_price());
            sortModel.setMin_price(cardTypeList.get(i).getMin_price());
            sortModel.setCard_id(cardTypeList.get(i).getCard_id());
            //汉字转换成拼音
            String pinyin = characterParser.getSelling(cardTypeList.get(i).getCard_name());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setLetter(sortString.toUpperCase());
            } else {
                sortModel.setLetter("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void beforeInit() {
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.iv_back)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void showToast(String msg, String state) {

    }

    @Override
    public void setCardType(CardTypeModel data) {
        if (data.getCode()==1){
            try {
                if (cardTypeList.size() != 0){
                    cardTypeList.clear();
                }
                cardTypeList= data.getData();
                list = filledData(cardTypeList);
                // 根据a-z进行排序源数据
                Collections.sort(list, pinyinComparator);
                myAdapter = new MyAdapter(this, list);
                listview.setAdapter(myAdapter);
                myAdapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(int position, View v) {
                        finish();
                        // 发布事件
                        EventBus.getDefault().post(new MessageEvent(list.get(position).getName(),list.get(position).getCard_id(),list.get(position).getDay(),list.get(position).getMin_price(),list.get(position).getMax_price()));
                    }
                });
            }catch (Exception e){
                e.printStackTrace();
            }

        }else {

        }
    }

    @Override
    public void showLoading() {
showLoadingDialog();
    }

    @Override
    public void hideLoading() {
dismissLoadingDialog();
    }

    @Override
    public Context getMyContext() {
        return this;
    }
}
